package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

/**
 * Connection to filters table
 * 
 * Performs DAO operations for the Filters
 * @author Sukhjinder K. Narula
 * @since June 2013
 * @version $Revision: 1.0 $
 */
public class FilterSqlDao implements FilterDao {
	
	// Connection
	private Connection conn;
    
    /**
     * Constructor
     * @param conn connection object for database
     */
    public FilterSqlDao(Connection conn) {
		this.conn = conn;
	}
    
    /**
     * Creates a new filter entry and returns the ID
     * @param properties 
    
     * @return int
     * @throws DaoException
     * @throws ModelException  * @see dao.FilterDao#create(HashMap<String,String>)
     */
    public int create(HashMap<String, String> properties) throws DaoException{
    	
    	int toReturn = -1;
    	try {
    		String sql = "INSERT INTO filters (UserId, Title, Subject, ToEmail, FromEmail, Body, FolderId) VALUES (?, ?,?, ?, ?, ?, ?) ;";
	    	PreparedStatement statement = conn.prepareStatement(sql);
	    	statement.setInt(1, Integer.valueOf(properties.get("UserId")));
	    	statement.setString(2, properties.get("Title"));
	    	statement.setString(3, properties.get("Subject"));
	    	statement.setString(4, properties.get("ToEmail"));
	    	statement.setString(5, properties.get("FromEmail"));
	    	statement.setString(6, properties.get("Body"));
	    	statement.setInt(7, Integer.valueOf(properties.get("FolderId")));
	    	statement.executeUpdate();	    	
	    	Statement st = conn.createStatement();
	    
        	ResultSet generatedKeys = st.executeQuery("SELECT seq FROM sqlite_sequence WHERE name = 'filters' ;");
        	if (generatedKeys.next()) {
        	    toReturn = generatedKeys.getInt("seq");
        	}	    		    
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
    	
    	
    	
    	return toReturn;
    }
    
    /**
     * Loads a filter row for given ID
     * @param id
    
    
     * @return HashMap<String,String>
     * @throws DaoException
     * @throws ModelException  * @see dao.FilterDao#load(int)
     */
    public HashMap<String, String> load(int id) throws DaoException{
    	
    	HashMap<String, String> toReturn;
    	try {
	    	String sql = "SELECT * FROM filters WHERE Id = ? LIMIT 1; ";
	    	PreparedStatement statement = null; 
	    	statement = conn.prepareStatement(sql);
	    	statement.setInt(1, id);
	    	ResultSet rs = statement.executeQuery();
	    	toReturn = new HashMap<String, String>();
	    	while (rs.next()) {
	    		toReturn.put("Id", String.valueOf(id));    		
	    		toReturn.put("UserId", String.valueOf("UserId"));    		
	    		toReturn.put("Title", rs.getString("Title"));
	    		toReturn.put("Subject", rs.getString("Subject"));
	    		toReturn.put("ToEmail", rs.getString("ToEmail"));   		
	    		toReturn.put("FromEmail", rs.getString("FromEmail"));
	    		toReturn.put("Body", rs.getString("Body"));
	    		toReturn.put("FolderId", rs.getString("FolderId"));
	    	}
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
    	return toReturn;
    }

    /**
     * Updates an filter row
     * @param properties
    
     * @throws DaoException
     * @throws ModelException  * @see dao.FilterDao#update(HashMap<String,String>)
     */
    public void update(HashMap<String, String> properties) throws DaoException {
    	try {
    		String sql = "UPDATE filters SET Title=?, Subject=?, ToEmail=?, FromEmail=?, Body=?, FolderId=? WHERE Id = ?; ";
        	PreparedStatement statement = conn.prepareStatement(sql);
        	statement.setString(1, properties.get("Title"));
        	statement.setString(2, properties.get("Subject"));
        	statement.setString(3, properties.get("ToEmail"));
        	statement.setString(4, properties.get("FromEmail"));
        	statement.setString(5, properties.get("Body"));
        	statement.setInt(6, Integer.valueOf(properties.get("FolderId")));
        	statement.setInt(7, Integer.valueOf(properties.get("Id")));
        	statement.executeUpdate();
    	} catch (SQLException e){
    		throw new DaoException(e.getMessage());
    	}
    }

	/**
	 * Deletes an filter row, given the id
	 * @param id
	
	 * @throws DaoException
	 * @throws ModelException  * @see dao.FilterDao#delete(int)
	 */
	public void delete(int id) throws DaoException{
		
		try {
			String sql = "DELETE FROM filters WHERE Id = ? ; ";
	    	PreparedStatement statement = conn.prepareStatement(sql);
	    	statement.setInt(1, id);
	    	statement.executeUpdate();
		} catch (SQLException e){
			throw new DaoException(e.getMessage());
		}
		
	}

	/**
	 * Given the userId, returns all the filters
	 * @param userId
	
	
	 * @return HashMap * @throws DaoException * @see dao.FilterDao#findByUserId(int)
	 */
	public HashMap<Integer, String[]> findByUserId(int userId) throws DaoException {
		HashMap<Integer, String[]> properties = new HashMap<>();
		int index = 0, key;
        PreparedStatement statement;
		try {
			statement = conn.prepareStatement("SELECT * FROM filters WHERE UserId = ? ;");
			statement.setString(1, String.valueOf(userId));
	        ResultSet rs = statement.executeQuery();
        	while (rs.next()){
        		String filterProperties[] = new String[7];
        		index = 0;
        		key = rs.getInt(1);
        		filterProperties[index++] = rs.getString(2);
        		filterProperties[index++] = rs.getString(3);
        		filterProperties[index++] = rs.getString(4);
        		filterProperties[index++] = rs.getString(5);
        		filterProperties[index++] = rs.getString(6);
        		filterProperties[index++] = rs.getString(7);
        		filterProperties[index++] = rs.getString(8);
        		properties.put(key, filterProperties);
        	}                   
	        rs.close();  
		} catch (SQLException e) {
			throw new DaoException(e.getMessage());
		}                  
        return properties;
	}	
	
}